<?php

require('config.php');
@include('custom.php');
require('libraries.php');

class CodeStudioController
{
	const SC_NONE = 1;
	const SC_SVN = 2;

	private $sourceControl = self::SC_NONE;
	private function output($data)
	{
		header('Content-type: application/json');
		echo '(' . json_encode($data) . ')';
	}
	private function outputFrame($data)
	{
		echo '<div id="data">(' . json_encode($data) . ')</div>';
	}
	public function setSourceControl($sourceControl)
	{
		$this->sourceControl = $sourceControl;
	}

	public function listDir($dir)
	{
		$response = array();
		if ($dir === '/') {
			$getDirs = $GLOBALS['config']['directories'];
			foreach ($getDirs as $dir) {
				$response['/'][] = array(basename($dir), $dir, true);
			}
		} else {
			$getDirs = array($dir);
	
			foreach ($getDirs as $dir) {
				$dirs = scandir($dir);
				$response[$dir] = array();
				foreach ($dirs as $subDir) {
					if ($subDir != '.' && $subDir != '..' && ($subDir != '.svn' || $GLOBALS['config']['sourceControl'] != 'svn')) {
						$response[$dir][] = array($subDir, $dir . DIRECTORY_SEPARATOR . $subDir, is_dir($dir . DIRECTORY_SEPARATOR . $subDir));
					}
				}
			}
		}

		$this->output($response);
	}
	public function getFile($fileName)
	{
		$this->output(array(
			'location'=>$fileName,
			'data'=>file_get_contents($fileName)
			));
	}
	public function serveFile($fileName)
	{
		$size = getimagesize($fileName);
		if ($size) {
			header('Content-Type: ' . $size['mime']);
		}
		
		echo file_get_contents($fileName);
		exit();
	}
	public function createFile($fileName)
	{
		$touched = touch($fileName);
	
		// SVN Source Control
		if ($this->sourceControl === SC_SVN) {
			$output = `svn add {$fileName}`;
		}
	
		$this->output(array(
			'status' => $touched,
			'message' => ($touched ? 'File created successfully' : 'Cannot create file ' . $fileName)
		));
	}
	public function createFolder($folderName)
	{
		$created = mkdir($folderName, 0777);
	
		// SVN Source Control
		if ($this->sourceControl === SC_SVN) {
			$output = `svn add {$folderName}`;
		}
	
		$this->output(array(
			'status' => $created,
			'message' => ($created ? 'Folder created successfully' : 'Cannot create folder ' . $folderName)
		));
	}
	public function delete($itemName)
	{
		// SVN Source Control
		if ($this->sourceControl === SC_SVN) {
			$output = `svn -f delete {$itemName}`;
			$deleted = true;
		} else {
			if (is_dir($itemName)) {
				$deleted = rmdir($itemName);
			} else {
				$deleted = unlink($itemName);
			}
		}
		$this->output(array(
			'status' => $deleted,
			'message' => ($deleted ? 'Deleted successfully' : 'Cannot delete ' . $itemName)
		));
	}
	public function saveFile($fileName)
	{
		$save = file_put_contents($fileName, $_POST['data']);

		$this->output(array(
			'status' => $save,
			'file'   => $fileName,
			'message' => ($save ? 'File saved successfully' : 'Cannot write file ' . $fileName)
		));
	}
	public function uploadFile($directory)
	{
		if ($_POST['unzip']) {
			$dirList = scandir($directory);
			`unzip {$_FILES['file']['tmp_name']} -d{$directory}`;
			$added = true;
			if ($this->sourceControl === SC_SVN) {
				$newFiles = array_diff($dirList, scandir($directory));
				foreach($newFiles as $file){
					$output = `svn add {$directory}/{$file}`;
				}
				$added = $added && true;
			}
		} else {
			$filePath = $directory . DIRECTORY_SEPARATOR . $_FILES['file']['name'];
			$added = move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
			if ($this->sourceControl === SC_SVN) {
				$output = `svn add {$itemName}`;
				$added = $added && true;
			}
		}


		$this->outputFrame(array(
			'status' => $added,
			'directory' => $directory,
			'message' => ($added ? 'File uploaded successfully' : 'Cannot upload file ' . $filePath)
		));
	}

	public function checkScript($file)
	{
		$pathInfo = pathinfo($file);
		$isErrors = false;
		if ($pathInfo['extension'] == 'php') {
			$errorCheck = `{$GLOBALS['config']['phpPath']} -l -d display_errors=On -d display_startup_errors=On -d error_reporting='E_ALL & ~E_NOTICE & ~E_STRICT' -d log_errors=Off {$file}`;

			if (strstr($errorCheck, 'Errors parsing') !== false) {
				$isErrors = true;
				$errorList = split("\n", $errorCheck);
				$errorCount = count($errorList)-2;
				for ($e=1; $e<$errorCount; ++$e) {
					if (preg_match('/(.+?): (.+?) on line (\d+)/i', $errorList[$e], $error)) {
						$errors[] = array(
							'type' => $error[1],
							'error' => $error[2],
							'line' => $error[3]
						);
					}
				}
			}

			$this->output(array(
				'isErrors' => $isErrors,
				'errors'   => $errors,
				'message'  => $errorCheck
			));
		}
	}
}

$action = $_GET['action'];
$controller = new CodeStudioController();
$controller->$action($_GET['name']);

switch ($GLOBALS['config']['sourceControl']) {
	case 'svn' :
		$controller->setSourceControl(CodeStudioController::SC_SVN);
		break;
}
